//
//  HomeViewController.swift
//  Weibo
//
//  Created by 杨雨哲 on 15/6/23.
//  Copyright © 2015年 yyz. All rights reserved.
//

import UIKit
import SVProgressHUD

class HomeViewController: BaseTableViewController, StatusCellDelegate {
    
    var statusesList: [Status]?{
        didSet{
            tableView.reloadData()
            refreshControl?.endRefreshing()
        }
    }
    
    lazy var rowHeightCache = [Int : CGFloat]()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
        visitorView?.setupUIInfo("visitordiscover_feed_image_house", message: "关注一些人，回这里看看有什么惊喜", isHome: true)
        
        if !userLogon {
            return
        }
        
        setupNavigationBar()
        prepareTableView()
        prepareRefresh()

    }
    
    func loadData(){
        
        refreshControl?.beginRefreshing()
        
        var since_id = statusesList?.first?.id ?? 0
        
        var max_id = 0
        
        if pullRefreshFlag{
            since_id = 0
            max_id = statusesList?.last?.id ?? 0
        }
        
        Status.loadStatus(since_id, max_id: max_id) { (statuses, error) -> () in
            
            if error != nil {
                SVProgressHUD.showErrorWithStatus("您的网络不给力")
                return
            }
            
            if statuses == nil{
                print("没有数据")
                return
            }
            
            // 跟踪转发微博
            print("加载了 \(statuses?.count) 条微博")
            
            if since_id > 0 {
                
                self.statusesList = statuses! + self.statusesList!
                
            }else if max_id > 0 {
                
                self.statusesList = self.statusesList! + statuses!
                self.pullRefreshFlag = false
                
            }else {
                // 初始刷新
                self.statusesList = statuses
            }
        }
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        visitorView?.startAnimation()
    }
    
    private func setupNavigationBar(){
        
        // 判断用户是否登录
        if sharedUserAccount == nil{
            return
        }
        
        // 设置导航栏按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", highlightedImageName: nil)
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", highlightedImageName: nil)
        print(navigationItem.rightBarButtonItem?.customView)
        // 1.1 获取 button
        let btn = navigationItem.rightBarButtonItem!.customView as! UIButton
        // 1.2 添加 target
        btn.addTarget(self, action: "showQRCode", forControlEvents: UIControlEvents.TouchUpInside)
        
        // 设置标题
        let name = sharedUserAccount!.name!
        let titleBtn = HomeTitleButton.button(name)
        
        titleBtn.addTarget(self, action: "titleButtonCliked", forControlEvents: UIControlEvents.TouchUpInside)
        
        navigationItem.titleView = titleBtn
        
    }
    
    func showQRCode(){
        let sb = UIStoryboard(name: "QRCode", bundle: nil)
        presentViewController(sb.instantiateInitialViewController()! , animated: true, completion: nil)
    }
    
    let popoverAnimator = PopoverAnimator()
    
    func titleButtonCliked(){
        let sb = UIStoryboard(name: "FriendGroup", bundle: nil)
        let vc = sb.instantiateViewControllerWithIdentifier("FriendGroupSB")
        
        vc.transitioningDelegate = popoverAnimator
        
        let x = (view.bounds.width - 200)*0.5
        popoverAnimator.presentFrame = CGRectMake(x, 56, 200, 300)
        
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc, animated: true, completion: nil)
    }
    
    // MARK: - Cell 的代理方法
    func statusCellDidSelectedPhoto(cell: StatusCell, photoIndex: Int) {
//        print(__FUNCTION__)
        if cell.status?.largePicURLs == nil{
            return
        }
        
        let vc = PhotoBrowerViewController(urls: (cell.status!.largePicURLs)!, index: photoIndex)
        
        presentedImageView.sd_setImageWithURL(cell.status!.picURLs![photoIndex])
        presentedImageView.frame = cell.screenFrame(photoIndex)
        presentedFrame = cell.fullScreenFrame(photoIndex)
        
        vc.transitioningDelegate = self
        vc.modalPresentationStyle = UIModalPresentationStyle.Custom
        presentViewController(vc, animated: true, completion: nil)
    }
    
    private lazy var presentedImageView = UIImageView()
    private var presentedFrame = CGRectZero


    // MARK: - Table view data source
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        print(statusesList?.count)

        return statusesList?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        
        let status = statusesList![indexPath.row]
        
        let ID = StatusCell.cellIdentifier(status)
        
        let cell = tableView.dequeueReusableCellWithIdentifier(ID, forIndexPath: indexPath) as! StatusCell
        
        cell.status = status
        
        cell.photoDelegate = self
        
        if indexPath.row == statusesList!.count - 1 {
            pullRefreshFlag = true
            loadData()
        }
        
        return cell
        
    }
    
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        let status = statusesList![indexPath.row]
        
        if rowHeightCache[status.id] != nil{
            return rowHeightCache[status.id]!
        }
        
        let ID = StatusCell.cellIdentifier(status)
        
        var cls: AnyClass = StatusNormalCell.self
        
        if ID == YZStatusForwardCellIdentifier{
            cls = StatusForwardCell.self
        }
        
        let cell = cls.new() as! StatusCell
        
        let height = cell.rowHeight(status)
        
        rowHeightCache[status.id] = height
        
        return height
        
    }
    
    private func prepareTableView() {
        // 注册可重用 cell
        tableView.registerClass(StatusForwardCell.self, forCellReuseIdentifier: YZStatusForwardCellIdentifier)
        tableView.registerClass(StatusNormalCell.self, forCellReuseIdentifier: YZStatusNormalCellIdentifier)
        // 取消分隔线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
    }
    
    private func prepareRefresh() {
        refreshControl = YZRefreshControl()
        
        // 添加监听方法
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
        
        // 加载数据
        loadData()
    }
    
    /// 上拉刷新标记
    private var pullRefreshFlag = false
    
    private var isPresented = false

}

extension HomeViewController: UIViewControllerTransitioningDelegate, UIViewControllerAnimatedTransitioning {
    
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        isPresented = true
        return self
    }
    
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        
        isPresented = false
        return self
    }
    
    func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
        return 0.5
    }
    
    func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
        
        let viewKey = isPresented ? UITransitionContextToViewKey : UITransitionContextFromViewKey
        let targetView = transitionContext.viewForKey(viewKey)
        
        if targetView == nil{
            return
        }
        
        if isPresented {
            transitionContext.containerView()?.addSubview(targetView!)
            targetView?.alpha = 0
            transitionContext.containerView()?.addSubview(presentedImageView)
            
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                self.presentedImageView.frame = self.presentedFrame
                }, completion: { (_) -> Void in
                    self.presentedImageView.removeFromSuperview()
                    targetView!.alpha = 1.0
                    transitionContext.completeTransition(true)
            })
        } else{
            UIView.animateWithDuration(transitionDuration(transitionContext), animations: { () -> Void in
                targetView?.alpha = 0
                }, completion: { (_) -> Void in
                    targetView?.removeFromSuperview()
                    transitionContext.completeTransition(true)
            })
        }
    }
}
